/**
 * Created by septimus on 15/1/3.
 */

app.controller('regController', function($scope, $http) {
    $scope.form = '';

    $scope.timer = 60;
    $scope.timeInterval;
    $scope.timerIsShow = false;

    var codeTimer = function() {
        var updateTimer = function() {
            $scope.timer--;
            if ($scope.timer <= 0) {
                $scope.timerIsShow = false;
                clearInterval($scope.timeInterval);
            }
        };
        $scope.timeInterval = setInterval(function() {
            $scope.$apply(updateTimer);
        }, 1000);

        $scope.timerIsShow = true;
        updateTimer();
    };

    $scope.getVerifyCode = function() {
        var url = urls.urlGetVerifyCode + '/phone/' + $scope.form.phone;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.codeMsg = '验证码已发送';
                codeTimer();
            } else {
                $scope.codeMsg = data.info;
            }
        });
    };

    $scope.submit = function() {
        if ($scope.regForm.$invalid) {
            return;
        }

        var url = urls.urlRegister,
            data = {
                user_name: $scope.form.userName,
                passwd: hex_md5($scope.form.psw),
                verficode: $scope.form.verifyCode,
                sex: $scope.form.sex,
                phone: $scope.form.phone
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    window.location.href = urls.urlResumeModify;
                } else {
                    alert(data.info);
                }
            });
    };
});

app.controller('forgotController', function($scope, $http) {
    $scope.form = '';

    $scope.timer = 60;
    $scope.timeInterval;
    $scope.timerIsShow = false;

    var codeTimer = function() {
        var updateTimer = function() {
            $scope.timer--;
            if ($scope.timer <= 0) {
                $scope.timerIsShow = false;
                clearInterval($scope.timeInterval);
            }
        };
        $scope.timeInterval = setInterval(function() {
            $scope.$apply(updateTimer);
        }, 1000);

        $scope.timerIsShow = true;
        updateTimer();
    };

    $scope.getVerifyCode = function() {
        var url = urls.urlLoginGetVerifyCode + '/phone/' + $scope.form.phone;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.codeMsg = '验证码已发送';
                //                alert("验证码已发送");
                codeTimer();
            } else {
                $scope.codeMsg = data.info;
                //                alert(data.info);
            }
        });
    };

    $scope.submit = function() {
        if ($scope.regForm.$invalid) {
            return;
        }

        var url = urls.urlResetPsw,
            data = {
                passwd: hex_md5($scope.form.psw),
                verfiCode: $scope.form.verifyCode,
                phone: $scope.form.phone
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    window.location.href = urls.urlLoginIndex;
                } else {
                    alert(data.info);
                }
            });
    };
});

app.controller('loginController', function($scope, $http) {
    $scope.form = {};
    if (localStorage.username && localStorage.psw) {
        $scope.form.phone = localStorage.username;
        $scope.form.psw = localStorage.psw;
    }

    $scope.submit = function() {
        $scope.loginForm.$setValidity('validate', true);
        if ($scope.loginForm.$invalid) {
            return;
        }

        var url = urls.urlLogin,
            data = {
                phone: $scope.form.phone,
                passwd: hex_md5($scope.form.psw),
                referer: $scope.referer
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    window.location.href = data.url;
                    if ($scope.form.autoLogin) {
                        localStorage.username = $scope.form.phone;
                        localStorage.psw = $scope.form.psw;
                    } else {
                        localStorage.username = '';
                        localStorage.psw = '';
                    }
                } else {
                    $scope.loginForm.$setValidity('validate', false);
                }
            });
    }
});

// 'I will publish mission' index
app.controller('publishIndexController', function($scope, $http, $q) {
    $scope.secondPart = [];
    $scope.keyword = '';
    $scope.userName = '';
    $scope.jobs = '';
    $scope.limit = 998;
    $scope.scroll = false;
    $scope.page = 0;
    $scope.isReqDone = false;

    if (isPC())
        window.location.href = urls.urlPublishPC;

    var defer = $q.defer();
    var promise = defer.promise;
    promise.then(getJobs($scope, $http))
        .then(function() {
            $scope.getPublishJobs();
        });
    defer.resolve($scope, $http);

    //    getJobs($scope, $http);
    $scope.durations = application.getDurations();

    //$scope.$watch('keyword', function() {
    //    $scope.search();
    //});

    $scope.jobClick = function(index) {
        $scope.jobs[index].active = !$scope.jobs[index].active;
        $scope.preferJobs = getActiveTag($scope.jobs, 'stat_name');
        $scope.preferJobsMeaning = transJobs($scope.preferJobs);
        //        $scope.search();
    };

    $scope.durationClick = function(index) {
        $scope.durations[index].active = !$scope.durations[index].active;
        $scope.preferDurations = getActiveTag($scope.durations, 'id');
        $scope.preferDurationMeaning = transDuration($scope.preferDurations);
        //        $scope.search();
    };

    $scope.toggle = function() {
        $scope.limit = Math.abs(1000 - $scope.limit);
        $scope.scroll = !$scope.scroll;
    };

    $scope.toProfile = function(id) {
        window.location.href = urls.urlProfile + '/user_id/' + id;
    };

    $scope.getPublishJobs = function() {
        $http.get(urls.urlFetchJobs).success(function(data) {
            $scope.preferJobs = '';
            $scope.preferDurations = '';
            $scope.search(0);
        });
    };
    // Search information of the second part with conditions.
    $scope.search = function(isRefresh) {
        $scope.page = isRefresh ? $scope.page + 1 : 0;
        if (!isRefresh) {
            $scope.secondPart = [];
        }

        $scope.isReqDone = false;
        var jobs = getActiveTag($scope.jobs, 'stat_name'),
            durations = getActiveTag($scope.durations, 'id');

        var url = urls.urlGetSecond + '?keyword=' + $scope.keyword + '&jobs=' + jobs + '&duration=' + durations
            + '&page=' + $scope.page;
        $http.get(url).success(function(data) {
            //            alert(JSON.stringify(data));
            if (data.status == 1) {
                var secondPartTemp = data.url;
                for (var i = 0; i < secondPartTemp.length; i++) {
                    secondPartTemp[i].degreeMeaning = genDegreeInfo(secondPartTemp[i]);
                }

                $scope.secondPart = Array.prototype.concat.call($scope.secondPart, secondPartTemp);
            }

            $scope.isReqDone = true;
            if ($scope.preferJobs == '' && $scope.preferDurations == '') {
                $scope.inputPrefer = 1;
            }
        });
    };

    //    $scope.search();
});

// 'Publish mission now' page
function publishSubmitController($scope, $http) {
    $scope.jobs = '';
    $scope.form = '';
    $scope.salary = application.getSalary();
    $scope.locations = application.getLocations();
    $scope.validTimes = application.getValidTime();

    $scope.isPhonePublic = 1;
    $scope.isAgent = 1;
    $scope.province = '';
    $scope.city = '';
    $scope.provinces = application.getProvinces();
    $scope.cities = new Array();

    getJobs($scope, $http);
    $scope.durations = application.getDurations();

    // Province and city cascade
    $scope.cascade = function() {
        //        var province = $(this).find("option:selected").text();
        $scope.city = '';
        $scope.cities = application.getCities()[$scope.province];
    };

    $scope.jobClick = function(index) {
        $scope.jobs[index].active = !$scope.jobs[index].active;
        $scope.form.jobMeaning = getActiveTag($scope.jobs, 'stat_name');
    };

    $scope.durationClick = function(index) {
        $scope.durations[index].active = !$scope.durations[index].active;
        $scope.form.duration = getActiveTag($scope.durations, 'id');
    };

    $scope.submit = function() {
        if ($scope.publishForm.$invalid) {
            return;
        }

        if ($scope.form.location1 == 3 && !isEmpty($scope.province)) {
            $scope.form.location2 = $scope.province + "，" + $scope.city;
            $scope.form.location2 = $scope.province;
            if (!isEmpty($scope.city)) {
                $scope.form.location2 += "，" + $scope.city;
            }
        } else {
            $scope.form.location2 = '';
        }

        if ($scope.form.salary1 != 1) {
            $scope.form.salary2 = '';
        }

        var url = urls.urlPublishMission,
            data = {
                mission_name: $scope.form.missionName,
                jobs: $scope.form.jobMeaning,
                duration: $scope.form.duration,
                salary1: $scope.form.salary1,
                salary2: $scope.form.salary2,
                location1: $scope.form.location1,
                location2: $scope.form.location2,
                description: $scope.form.description,
                valid_time: $scope.form.validTime,
                isagent: ($scope.isAgent * 1) + 1,
                isphone_public: ($scope.isPhonePublic * 1) + 1
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    window.location.href = urls.urlManage;
                } else {
                    alert(data.info);
                }
            });
    };
}

// Manage mission index
function manageController($scope, $http) {
    $scope.missionUndone = '';
    $scope.missionDone = '';

    $scope.getMission = function() {
        $http.get(urls.urlManageGetInfo).success(function(data) {
            if (data.status == 1) {
                if (data.url[1] != null) {
                    $scope.missionDone = data.url[1];
                    for (var i = 0; i < $scope.missionDone.length; i++) {
                        $scope.missionDone[i].durationMeaning = transDuration($scope.missionDone[i].duration);
                        $scope.missionDone[i].salaryMeaning = transSalary($scope.missionDone[i].salary1, $scope.missionDone[i].salary2);
                        $scope.missionDone[i].locationMeaning = transLocation($scope.missionDone[i].location1, $scope.missionDone[i].location2);
                    }
                }

                if (data.url[0] != null) {
                    $scope.missionUndone = data.url[0];
                    for (var i = 0; i < $scope.missionUndone.length; i++) {
                        $scope.missionUndone[i].durationMeaning = transDuration($scope.missionUndone[i].duration);
                        $scope.missionUndone[i].salaryMeaning = transSalary($scope.missionUndone[i].salary1, $scope.missionUndone[i].salary2);
                        $scope.missionUndone[i].locationMeaning = transLocation($scope.missionUndone[i].location1, $scope.missionUndone[i].location2);
                    }
                }

            } else {
                $scope.missionDone = '';
                $scope.missionUndone = '';
            }
        });
    };

    $scope.getMission();
}

// Manage mission detail
function manageDetailController($scope, $http, $q) {
    $scope.mission = '';
    $scope.isPhonePublic = false;
    $scope.isAgentPublic = false;
    $scope.follower = '';
    $scope.receiver = '';

    $scope.form = '';
    $scope.jobs = '';
    $scope.salary2 = '';
    $scope.location2 = '';
    $scope.salary = application.getSalary();
    $scope.locations = application.getLocations();
    $scope.province = '';
    $scope.city = '';
    $scope.provinces = application.getProvinces();
    $scope.cities = new Array();

    $scope.rank = 0;

    //    $scope.jobMeaning = '';
    $scope.durationMeaning = '';
    $scope.salaryMeaning = '';
    $scope.locationMeaning = '';

    // Enable republishing
    $scope.modified = false;
    $scope.status = 2;

    // Get jobs before setting active tag
    var defer = $q.defer();
    defer.promise
        .then(getJobs($scope, $http))
        .then(function($scope) {
            $scope.getDetail()
        });
    defer.resolve($scope, $http);
    $scope.durations = application.getDurations();
    $scope.validTimes = application.getValidTime();

    // Change to normal style after input done
    $('body').on('click', function(event) {
        if ($(event.target).closest('.input-modify').length == 0) {
            $scope.clearInputs();
            $scope.$apply();
        }
    });

    // Check for modifying
    $('input, select, textarea').on('change', function() {
        $scope.modified = true;
    });

    $scope.$watch('status', function() {
        if ($scope.status == 1) {
            $('input, select, textarea').removeAttr('disabled');
            $('.dl-modify dd span').removeClass('text-link');
            $('#missionName').addClass('text-name');
        } else {
            $('input, select, textarea').attr('disabled', 'disabled');
            $('.dl-modify dd span').addClass('text-link');
            $('#missionName').removeClass('text-name');
        }
    });

    // Province and city cascade
    $('#selectP').on('change', function() {
        var province = $(this).find("option:selected").text();
        $scope.city = '';
        $scope.cities = application.getCities()[province];
    });

    $scope.clearInputs = function() {
        $scope.inputMissionName =
            $scope.inputJobs =
            $scope.inputDuration =
            $scope.inputSalary =
            $scope.inputLocation =
            $scope.inputDesc = 0;
    };

    $scope.jobClick = function(index) {
        $scope.jobs[index].active = !$scope.jobs[index].active;
        $scope.mission.jobs = getActiveTag($scope.jobs, 'stat_name');
        $scope.modified = true;
    };

    $scope.durationClick = function(index) {
        $scope.durations[index].active = !$scope.durations[index].active;
        $scope.mission.duration = getActiveTag($scope.durations, 'id');
        $scope.durationMeaning = transDuration($scope.mission.duration);
        $scope.modified = true;
    };

    // Translate variables on changing
    $scope.transSalary = function() {
        $scope.salaryMeaning = transSalary($scope.mission.salary1, $scope.mission.salary2)
        return $scope.salaryMeaning;
    };

    $scope.transLocation = function() {
        if (!isEmpty($scope.province)) {
            $scope.mission.location2 = $scope.province;
            if (!isEmpty($scope.city)) {
                $scope.mission.location2 += "，" + $scope.city;
            }
        } else {
            $scope.mission.location2 = '';
        }

        $scope.locationMeaning = transLocation($scope.mission.location1, $scope.mission.location2);
        return $scope.locationMeaning;
    };

    $scope.getDetail = function() {
        var url = urls.urlManageDetail + '/mission_id/' + $('#missionId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.mission = data.url;
                $scope.isPhonePublic = ($scope.mission.isphone_public == 2);
                $scope.isAgentPublic = ($scope.mission.agent == 2);
                $scope.durationMeaning = transDuration($scope.mission.duration);
                if ($scope.mission.location2 != '') {
                    $scope.province = $scope.mission.location2.split(',')[0];
                    $scope.cities = application.getCities()[$scope.province];
                    if (!isEmpty($scope.mission.location2.split(',')[1])) {
                        $scope.city = $scope.mission.location2.split(',')[1];
                    } else {
                        $scope.city = '';
                    }
                }
                //                $scope.status = $scope.mission.status;
                setActiveTag($scope.mission.jobs, $scope.jobs, 'stat_name');
                setActiveTag($scope.mission.duration, $scope.durations, 'id');
            } else {
                $scope.mission = '';
                $scope.status = 2;
            }
        });
    };

    // id - judge if it's 1 - receiver or 0 - follower
    $scope.favUser = function(id) {
        if (id == 1) {
            favUser($scope.receiver.user_id, $http);
            $scope.receiver.hasFavored = 2;
        } else {
            favUser($scope.follower.user_id, $http);
            $scope.follower.hasFavored = 2;
        }
        $scope.getDetail();
    };

    $scope.delFavUser = function(id) {
        if (id == 1) {
            delFavUser($scope.receiver.user_id, $http);
            $scope.receiver.hasFavored = 1;
        } else {
            delFavUser($scope.follower.user_id, $http);
            $scope.follower.hasFavored = 1;
        }
    };

    $scope.getFollowerModal = function(index) {
        if ($scope.mission.status != 2) {
            if (!isEmpty($scope.mission.follow)) {
                $scope.follower = $scope.mission.follow[index];
                $scope.follower.hasFavored = $scope.follower.collect_status;
            }
            $('#followerModal').modal('show');
        } else {
            if (!isEmpty($scope.mission.follow[index])) {
                window.location.href = urls.urlProfile + '/user_id/' + $scope.mission.follow[index].user_id;
            }
        }
    };

    $scope.getReceiverModal = function(index) {
        if ($scope.mission.status != 2) {
            if (!isEmpty($scope.mission.receive)) {
                $scope.receiver = $scope.mission.receive[index];
                $scope.receiver.hasFavored = $scope.receiver.collect_status;
                $scope.receiver.hasEvaluated = (!isEmpty($scope.receiver.evaluate) * 1);
            }
            $('#receiverModal').modal('show');
        } else {
            if (!isEmpty($scope.mission.receive[index])) {
                window.location.href = urls.urlProfile + '/user_id/' + $scope.mission.receive[index].user_id;
            }
        }
    };

    $scope.modify = function() {
        $scope.status = 1;
        $scope.modified = 1;
    };

    $scope.manage = function() {
        $scope.status = 2;
        $scope.modified = 0;
    };

    $scope.select = function() {
        var url = urls.urlProfileSelect,
            data = {
                mission_id: $scope.mission.mission_id,
                follower_id: $scope.follower.user_id
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {

                } else {
                    //                    alert(data.info);
                }
                $('#followerModal').modal('hide');
                $scope.follower = '';
                $scope.getDetail();
            });
    };

    $scope.evaluate = function() {
        var url = urls.urlManageEvaluate,
            data = {
                evaluate: $scope.rank,
                mission_id: $scope.mission.mission_id,
                user_id: $scope.receiver.user_id
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {

                } else {
                    //                    alert(data.info);
                }
                $('#receiverModal').modal('hide');
                $scope.receiver = '';
                $scope.getDetail();
            });
    };

    $scope.refuse = function() {
        var url = urls.urlManageRefuse,
            data = {
                mission_id: $scope.mission.mission_id,
                user_id: $scope.receiver.user_id
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {

                } else {
                    //                    alert(data.info);
                }
                $('#receiverModal').modal('hide');
                $scope.receiver = '';
                $scope.getDetail();
            });
    };

    $scope.submit = function() {
        if ($scope.mission.location1 == 3 && !isEmpty($scope.province)) {
            $scope.mission.location2 = $scope.province;
            if (!isEmpty($scope.city)) {
                $scope.mission.location2 += "，" + $scope.city;
            }
        } else {
            $scope.mission.location2 = '';
        }

        if ($scope.mission.salary1 != 1) {
            $scope.mission.salary2 = '';
        }

        var url = urls.urlManageSubmit,
            data = {
                mission_id: $scope.mission.mission_id,
                mission_name: $scope.mission.mission_name,
                jobs: $scope.mission.jobs,
                duration: $scope.mission.duration,
                salary1: $scope.mission.salary1,
                salary2: $scope.mission.salary2,
                location1: $scope.mission.location1,
                location2: $scope.mission.location2,
                description: $scope.mission.description,
                valid_time: $scope.mission.valid_time,
                isagent: ($scope.isAgentPublic * 1) + 1,
                isphone_public: ($scope.isPhonePublic * 1) + 1
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    window.location.href = urls.urlManage;
                } else {
                    alert(data.info);
                }
            });
    };

    $scope.finish = function(opt) {
        for (var i = 0; i < $scope.mission.receive; i++) {
            $scope.mission.receive[i].is_selected = true;
        }

        var url = urls.urlManageFinish,
            data = {
                mission_id: $scope.mission.mission_id,
                actor_info: $scope.mission.receive,
                evaluate: opt
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    window.location.href = urls.urlManage;
                } else {
                    alert(data.info);
                }
            });
    };

    $scope.clearInputs();
}

// Manage received mission index
function manageRecvController($scope, $http) {
    $scope.missionUndone = '';
    $scope.missionDone = '';
    $scope.missionPicked = '';

    $scope.getMission = function() {
        $http.get(urls.urlManageRecvGetInfo).success(function(data) {
            if (data.status == 1) {
                if (!isEmpty(data.url[0])) {
                    $scope.missionUndone = data.url[0];
                    for (var i = 0; i < $scope.missionUndone.length; i++) {
                        $scope.missionUndone[i].durationMeaning = transDuration($scope.missionUndone[i].duration);
                        $scope.missionUndone[i].salaryMeaning = transSalary($scope.missionUndone[i].salary1, $scope.missionUndone[i].salary2);
                        $scope.missionUndone[i].locationMeaning = transLocation($scope.missionUndone[i].location1, $scope.missionUndone[i].location2);
                    }
                }

                if (!isEmpty(data.url[1])) {
                    $scope.missionPicked = data.url[1];
                    for (var i = 0; i < $scope.missionPicked.length; i++) {
                        $scope.missionPicked[i].durationMeaning = transDuration($scope.missionPicked[i].duration);
                        $scope.missionPicked[i].salaryMeaning = transSalary($scope.missionPicked[i].salary1, $scope.missionPicked[i].salary2);
                        $scope.missionPicked[i].locationMeaning = transLocation($scope.missionPicked[i].location1, $scope.missionPicked[i].location2);
                    }
                }

                if (!isEmpty(data.url[2])) {
                    $scope.missionDone = data.url[2];
                    for (var i = 0; i < $scope.missionDone.length; i++) {
                        $scope.missionDone[i].durationMeaning = transDuration($scope.missionDone[i].duration);
                        $scope.missionDone[i].salaryMeaning = transSalary($scope.missionDone[i].salary1, $scope.missionDone[i].salary2);
                        $scope.missionDone[i].locationMeaning = transLocation($scope.missionDone[i].location1, $scope.missionDone[i].location2);
                    }
                }
            } else {
                $scope.missionDone = '';
                $scope.missionUndone = '';
                $scope.missionPicked = '';
            }
        });
    };

    $scope.getMission();
}


// 'I will fetch mission' index
app.controller('fetchIndexController', function($scope, $http, $q) {
    $scope.userName = '';
    $scope.jobs = '';
    $scope.limit = 998;
    $scope.scroll = false;

    if (isPC())
        window.location.href = urls.urlFetchPC;

    var defer = $q.defer();
    defer.promise
        .then(getJobs($scope, $http))
        .then(function($scope) {
            $scope.search();
        });
    defer.resolve($scope, $http);
    $scope.durations = application.getDurations();

    $scope.jobClick = function(index) {
        $scope.jobs[index].active = !$scope.jobs[index].active;
        //        $scope.search();
    };

    $scope.durationClick = function(index) {
        $scope.durations[index].active = !$scope.durations[index].active;
        //        $scope.search();
    };

    $scope.toggle = function() {
        $scope.limit = Math.abs(1000 - $scope.limit);
        $scope.scroll = !$scope.scroll;
    };

    // Search information of the second part with conditions.
    $scope.search = function() {
        var jobs = getActiveTag($scope.jobs, 'stat_name'),
            durations = getActiveTag($scope.durations, 'id');

        var url = urls.urlFetchMission + '?jobs=' + jobs + '&duration=' + durations;
        $http.get(url).success(function(data) {
            //            alert(JSON.stringify(data));
            if (data.status == 1) {
                $scope.missions = data.url;
                for (var i = 0; i < $scope.missions.length; i++) {
                    $scope.missions[i].durationMeaning = transDuration($scope.missions[i].duration);
                    $scope.missions[i].salary = transSalary($scope.missions[i].salary1, $scope.missions[i].salary2);
                    $scope.missions[i].location = transLocation($scope.missions[i].location1, $scope.missions[i].location2);
                }
            } else {
                $scope.missions = '';
            }
        });
    };

    //    $scope.search();
});

// Accurate search in Fetcher
app.controller('fetchSearchController', function($scope, $http, $q) {
    $scope.userName = '';
    $scope.keyword = '';
    $scope.jobs = '';
    $scope.limit = 998;
    $scope.scroll = false;

    if (isPC())
        window.location.href = urls.urlFetchPC;

    var defer = $q.defer();
    defer.promise
        .then(getJobs($scope, $http))
        .then(function() {
            $scope.getFetchJobs();
        });
    defer.resolve($scope, $http);
    $scope.durations = application.getDurations();

    $scope.jobClick = function(index) {
        $scope.jobs[index].active = !$scope.jobs[index].active;
        $scope.preferJobs = getActiveTag($scope.jobs, 'stat_name');
        $scope.preferJobsMeaning = transJobs($scope.preferJobs);
    };

    $scope.durationClick = function(index) {
        $scope.durations[index].active = !$scope.durations[index].active;
        $scope.preferDurations = getActiveTag($scope.durations, 'id');
        $scope.preferDurationMeaning = transDuration($scope.preferDurations);
        //        $scope.search();
    };

    $scope.toggle = function() {
        $scope.limit = Math.abs(1000 - $scope.limit);
        $scope.scroll = !$scope.scroll;
    };

    $scope.getFetchJobs = function() {
        $http.get(urls.urlFetchJobs).success(function(data) {
            if (data.status == 1) {
                $scope.preferJobs = data.url.jobs;
                $scope.preferDurations = data.url.duration;
                setActiveTag($scope.preferJobs, $scope.jobs, 'stat_name');
                setActiveTag($scope.preferDurations, $scope.durations, 'id');
                $scope.preferJobsMeaning = transJobs($scope.preferJobs);
                $scope.preferDurationMeaning = transDuration($scope.preferDurations);
            } else {
                $scope.preferJobs = '';
                $scope.preferDurations = '';
            }
            $scope.search();
        });
    };

    // Search information of the second part with conditions.
    $scope.search = function() {
        var jobs = getActiveTag($scope.jobs, 'stat_name'),
            durations = getActiveTag($scope.durations, 'id');

        var url = urls.urlFetchSearch + '?keyword=' + $scope.keyword + '&jobs=' + jobs + '&duration=' + durations;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.missions = data.url;
                for (var i = 0; i < $scope.missions.length; i++) {
                    $scope.missions[i].durationMeaning =
                        transDuration($scope.missions[i].duration);
                    $scope.missions[i].salary =
                        transSalary($scope.missions[i].salary1, $scope.missions[i].salary2);
                    $scope.missions[i].location =
                        transLocation($scope.missions[i].location1, $scope.missions[i].location2);
                    //                    $scope.missions[i].time = getTimePast($scope.missions[i].publish_time);
                }
            } else {
                $scope.missions = '';
            }

            if (isEmpty($scope.preferJobs) && isEmpty($scope.preferDurations)) {
                $scope.inputPrefer = 1;
            }
        });
    };

    //    $scope.$watch('keyword', function() {
    //        $scope.search();
    //    });

    //    $scope.search();
});

function profileController($scope, $http) {
    $scope.userBase = '';
    $scope.trustInfo = '';
    $scope.firstInfo = '';
    $scope.secondInfo = '';
    $scope.missions = '';
    $scope.missionId = '';
    $scope.phone = '';
    $scope.images = new Array();

    $scope.hasFavored = 1;
    $scope.hasTrusted = 1;
    $scope.isPublic = 1;
    $scope.isFirst = false;

    $scope.judgeOrigin = function() {
        $scope.isFirst = (!isEmpty($scope.isPublish) && $scope.isPublish == 0);
    };

    $scope.getBaseInfo = function() {
        var url = urls.urlProfileBase + '/user_id/' + $('#userId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.userBase = data.url;
                if (isEmpty($scope.userBase.image_url)) {
                    $scope.userBase.image_url = paths.pathDefaultAvatar;
                }
                if ($scope.userBase.sex == 2) {
                    $scope.userBase.sexMeaning = '女';
                } else {
                    $scope.userBase.sexMeaning = '男';
                }
                $scope.userBase.degreeMeaning = genDegreeInfo($scope.userBase);
                if ($scope.userBase.collect_status == 2)
                    $scope.hasFavored = 2;
                else
                    $scope.hasFavored = 1;
            } else {
                $scope.userBase = '';
                $scope.hasFavored = 1;
            }
        });
    };

    $scope.getTrustInfo = function() {
        var url = urls.urlGetTrustInfo + '/user_id/' + $('#userId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.trustInfo = data.url;
                $scope.hasTrusted = $scope.trustInfo.is_trusted;
            } else {
                $scope.trustInfo = '';
                $scope.hasTrusted = 1;
            }
        });
    };

    $scope.getFirstInfo = function() {
        var url = urls.urlGetFirstInfo + '/user_id/' + $('#userId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.firstInfo = data.url;
                if (!isEmpty($scope.firstInfo.mission)) {
                    var missions = $scope.firstInfo.mission;
                    for (var i = 0; i < missions.length; i++) {
                        missions[i].durationMeaning = transDuration(missions[i].duration);
                        missions[i].salary = transSalary(missions[i].salary1, missions[i].salary2);
                        missions[i].location = transLocation(missions[i].location1, missions[i].location2);
                    }
                } else {
                    $scope.firstInfo = '';
                }
            }
        });
    };

    $scope.getSecondInfo = function() {
        var url = urls.urlGetSecondInfo + '/user_id/' + $('#userId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.secondInfo = data.url;
                $scope.isPublic = $scope.secondInfo.public_resume;
                $scope.secondInfo.degreeMeaning = genDegreeInfo($scope.secondInfo);

                if (!isEmpty($scope.secondInfo.resume_att)) {
                    $scope.attach = $scope.secondInfo.resume_att;
                    $scope.images = new Array();
                    if (!isEmpty($scope.attach.image_url)) {
                        for (var i = 0; i < $scope.attach.image_url.length; i++) {
                            for (img in $scope.attach.image_url[i]) {
                                $scope.images.push({
                                    name: img,
                                    url: $scope.attach.image_url[i][img]
                                });
                            }
                        }
                    }
                }
            } else {
                $scope.secondInfo = '';
                $scope.isPublic = 1;
                $scope.images = new Array();
            }
        });
    };

    $scope.getPhone = function() {
        var url = urls.urlTaskContact + '/publisher_id/' + $('#userId').val();;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $('#contactModal').modal('show');
                $scope.phone = data.url.phone;
            } else {
                $scope.phone = '';
            }
        });
    };

    $scope.getProject = function() {
        $('#selectModal').modal('show');
        $http.get(urls.urlGetProj).success(function(data) {
            if (data.status == 1) {
                $scope.missions = data.url;
            } else {
                $scope.missions = '';
            }
        });
    };

    $scope.scaleAttach = function(imageIndex) {
        $scope.scaleTarget = $scope.attach[imageIndex].image_url;
    };

    $scope.getReportModal = function() {
        $('#reportModal').modal('show');
    };

    $scope.getPublicModal = function() {
        $('#publicModal').modal('show');
    };

    $scope.getTrustNum = function() {
        if (!isEmpty($scope.trustInfo.truster_arr)) {
            return $scope.trustInfo.truster_arr.length;
        } else {
            return 0;
        }
    };

    $scope.trust = function() {
        var url = urls.urlProfileTrust + '/user_id/' + $('#userId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.hasTrusted = 2;
                $scope.getTrustInfo();
            } else {

            }
        });
    };

    $scope.delTrust = function() {
        var url = urls.urlProfileDelTrust + '/user_id/' + $('#userId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.hasTrusted = 1;
                $scope.getTrustInfo();
            } else {

            }
        });
    };

    $scope.select = function() {
        var url = urls.urlProfileSelect,
            data = {
                mission_id: $scope.missionId,
                follower_id: $('#userId').val()
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {

                } else {
                    //                    alert(data.info);
                }
                $('#selectModal').modal('hide');
                $scope.missions = '';
            });
    };

    $scope.report = function() {
        var url = urls.urlProfileReport,
            data = {
                user_id: $('#userId').val(),
                content: $scope.reportCont
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {

                } else {
                    //                    alert(data.info);
                }
                $('#reportModal').modal('hide');
                $scope.reportCont = '';
            });
    };

    // Be public to one
    $scope.publicToOne = function() {
        var url = urls.urlProfilePublicToOne,
            data = {
                user_id: $('#userId').val()
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    $scope.getBaseInfo();
                } else {
                    //                    alert(data.info);
                }
            });
    };

    // Send message to inform one to be public
    $scope.public = function() {
        var url = urls.urlProfilePublic,
            data = {
                user_id: $('#userId').val(),
                message: $scope.publicCont
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {

                } else {
                    //                    alert(data.info);
                }
                $('#publicModal').modal('hide');
                $scope.publicCont = '';
            });
    };

    $scope.favUser = function() {
        favUser($('#userId').val(), $http);
        $scope.getBaseInfo();
    };

    $scope.delFavUser = function() {
        delFavUser($('#userId').val(), $http);
        $scope.getBaseInfo();
    };

    $scope.getBaseInfo();
    $scope.getTrustInfo();
    $scope.getFirstInfo();
    $scope.getSecondInfo();
}

// Mission detail
function taskController($scope, $http) {
    $scope.mission = '';
    $scope.publisher = '';
    $scope.phone = '';

    $scope.hasFavored = 1;

    // Modal not supported in current version
    $('#modalSubmit').on('click', function() {
        $scope.receive();
    });

    $scope.getTaskInfo = function() {
        var url = urls.urlTask + '/mission_id/' + $('#missionId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.mission = data.url;
                $scope.mission.durationMeaning = transDuration($scope.mission.duration);
                $scope.mission.salaryMeaning = transSalary($scope.mission.salary1, $scope.mission.salary2);
                $scope.mission.locationMeaning = transLocation($scope.mission.location1, $scope.mission.location2);
                if ($scope.mission.collect_status == 2)
                    $scope.hasFavored = 2;
                else
                    $scope.hasFavored = 1;

                if (data.url.publisher.length != 0) {
                    $scope.publisher = data.url.publisher;
                    if (isEmpty($scope.publisher.image_url)) {
                        $scope.publisher.image_url = paths.pathDefaultAvatar;
                    }
                } else {
                    $scope.publisher = '';
                }
            } else {
                $scope.mission = '';
                $scope.hasFavored = 1;
            }
        });
    };

    $scope.favMission = function() {
        var url = urls.urlFavMission + '/mission_id/' + $('#missionId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.getTaskInfo();
            } else {

            }
        });
    };

    $scope.delFavMission = function() {
        var url = urls.urlFavDelMission + '/mission_id/' + $('#missionId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.getTaskInfo();
            } else {

            }
        });
    };

    // Fetch mission
    $scope.receive = function() {
        var url = urls.urlTaskRecv,
            data = {
                mission_id: $('#missionId').val(),
                message: $('#content').val()
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {

                } else {
                    //                    alert(data.info);
                }
                $('#msgModal').modal('hide');
                $('#msgModal .modal-header').find('h4').text('');
                $scope.getTaskInfo();
            });
    };

    $scope.getPhone = function() {
        var url = urls.urlTaskContact + '/publisher_id/' + $scope.mission.publisher_id;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $('#contactModal').modal('show');
                $scope.phone = data.url.phone;
            } else {
                $scope.phone = '';
            }
        });
    };

    $scope.showModal = function() {
        $('#msgModal').modal('show');
        $('#msgModal .modal-header').find('h4').text($scope.mission.mission_name);
    };

    $scope.getTaskInfo();
}

// Resume Index
function resumeController($scope, $http, $timeout) {
    $scope.resumeBase = '';
    $scope.isPublic = 1;
    $scope.intro = '';
    $scope.attachImages = new Array();

    $scope.projectName = '';
    $scope.role = '';

    $scope.expId = '';
    $scope.oldOrder = '';
    $scope.newOrder = '';

    $scope.$watch('isPublic', function() {
        $scope.submitIsPublic();
    });

    $('#inputIntro').on('change', function() {
        $scope.submitIntro();
    });

    $('#inputProjName').on('change', function() {
        $scope.submitExp();
    });

    $('#inputRole').on('change', function() {
        $scope.submitExp();
    });

    $scope.dragInit = function() {
        $timeout(function() {
            $('.li-resume-normal').draggable({
                axis: 'y',
                containment: 'parent',
                revert: 'invalid',
                handle: $('.handle-resume'),
                start: function(event, ui) {
                    $scope.oldOrder = parseInt($(this).attr('order'));
                    $scope.expId = $(this).attr('id');
                    $(this).removeClass('ui-droppable');
                }
            });
            $('.li-resume-normal').droppable({
                tolerance: 'touch',
                drop: function(event, ui) {
                    var height = $(event.target).height();
                    var topOffset = parseInt(ui.draggable.css('top'), 10);
                    var dist = topOffset % height;
                    if (topOffset != 0 && !isNaN(topOffset)) {
                        $(ui.draggable).removeAttr('style');
                        $(event.target).removeAttr('style');
                        if ((dist < 0 && dist > -(height - 24)) || dist > 0) {
                            $(event.target).after(ui.draggable);
                        } else {
                            $(event.target).before(ui.draggable);
                        }
                        $scope.newOrder = parseInt($(event.target).attr('order'));

                        $(ui.draggable).attr('style', 'position: relative');
                        $(event.target).attr('style', 'position: relative');
                        $(ui.draggable).addClass('ui-droppable');

                        if (!isNaN($scope.oldOrder) && !isNaN($scope.newOrder)) {
                            $scope.setExpOrder();
                        }
                    }

                }
            });
        }, 500);
    };

    $scope.setExpOrder = function() {
        var url = urls.urlResumeOrderExp + '?exp_id=' + $scope.expId + '&old_order=' + $scope.oldOrder + '&new_order=' + $scope.newOrder;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                if ($scope.resumeBase != '') {
                    $scope.resumeBase.experience = data.url;
                    $scope.dragInit();
                }
            } else {

            }
        });
    };

    $scope.getBaseInfo = function() {
        var url = urls.urlResumeBase;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.resumeBase = data.url;
                $scope.isPublic = $scope.resumeBase.is_public;
                $scope.intro = $scope.resumeBase.introduction;
                if ($scope.resumeBase.sex == 2) {
                    $scope.resumeBase.sexMeaning = '女';
                } else {
                    $scope.resumeBase.sexMeaning = '男';
                }
                $scope.resumeBase.jobsMeaning = transJobs($scope.resumeBase.jobs);
                $scope.resumeBase.durationMeaning = transDuration($scope.resumeBase.duration);
                $scope.resumeBase.degreeMeaning = genDegreeInfo($scope.resumeBase);

                // Get attachment image array
                $scope.attachImages = new Array();
                if (!isEmpty($scope.resumeBase.resume_att)) {
                    for (var i = 0; i < $scope.resumeBase.resume_att.image.length; i++) {
                        for (img in $scope.resumeBase.resume_att.image[i]) {
                            $scope.attachImages.push({
                                name: img,
                                url: $scope.resumeBase.resume_att.image[i][img]
                            });
                        }
                    }
                }

                $scope.dragInit();
            } else {
                $scope.resumeBase = '';
            }
        });
    };

    $scope.submitIsPublic = function() {
        var url = urls.urlResumeSetPublic,
            data = {
                is_public: $scope.isPublic
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {

                } else {
                    //                    alert(data.info);
                }
            });
    };

    $scope.submitIntro = function() {
        var url = urls.urlResumeSetIntro,
            data = {
                introduction: $scope.intro
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {

                } else {
                    alert(data.info);
                }
            });
    };

    $scope.submitExp = function() {
        var url = urls.urlResumeAddExp,
            data = {
                resume_id: $scope.resumeBase.resume_id,
                project_name: $scope.projectName,
                role: $scope.role
            };

        if ($scope.projectName != '' && $scope.role != '') {
            $http.post(url, data, postCfg(data))
                .success(function(data) {
                    if (data.status == 1) {
                        $scope.projectName = '';
                        $scope.role = '';
                        $scope.getBaseInfo();
                    } else {
                        alert(data.info);
                    }
                });
        }
    };

    $scope.getBaseInfo();
}

// Edit experience description page
function resumeEditController($scope, $http) {
    $scope.attach = '';
    $scope.scaleTarget = '';
    $scope.inputProjName = 0;
    $scope.inputRole = 0;

    // Change to normal style after input done
    $('body').on('click', function(event) {
        if ($(event.target).closest('.input-modify').length == 0) {
            if ($scope.inputProjName == 1) {
                $scope.submitProjName();
            }
            if ($scope.inputRole == 1) {
                $scope.submitRole();
            }
            $scope.clearInputs();
        }
        $scope.$apply();
    });

    $scope.clearInputs = function() {
        $scope.inputProjName =
            $scope.inputRole = 0;
    };

    $scope.getExpAttach = function() {
        var url = urls.urlResumeGetExp + '/exp_id/' + $scope.expId;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.attach = data.url;
            } else {
                $scope.attach = '';
            }
        });
    };

    $scope.scaleAttach = function(imageIndex) {
        $scope.scaleTarget = $scope.attach[imageIndex].image_url;
    };

    $scope.delAttach = function(imageIndex) {
        var url = urls.urlResumeDelPhotoExp,
            data = {
                exp_id: $scope.expId,
                image_url: $scope.attach[imageIndex].image_url
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    $scope.getExpAttach();
                } else {

                }
            });
    };

    $scope.submitProjName = function() {
        var url = urls.urlResumeSetProjName,
            data = {
                exp_id: $scope.expId,
                project_name: $scope.projName
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {

                } else {
                    //                    alert(data.info);
                }
            });
    };

    $scope.submitRole = function() {
        var url = urls.urlResumeSetRole,
            data = {
                exp_id: $scope.expId,
                role: $scope.role
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {

                } else {
                    //                    alert(data.info);
                }
            });
    };

    $scope.submitDesc = function() {
        var url = urls.urlResumeSetExpDesc,
            data = {
                exp_id: $scope.expId,
                description: $scope.desc
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {

                } else {
                    //                    alert(data.info);
                }
            });
    };

    $scope.submitUrl = function() {
        var url = urls.urlResumeSetExpUrl,
            data = {
                exp_id: $scope.expId,
                url: $scope.url
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {

                } else {
                    //                    alert(data.info);
                }
            });
    };
}

// Edit profile in resume
app.controller('resumeProfileController', ['$scope', '$http', '$q', function($scope, $http, $q) {
    $scope.user = '';
    $scope.jobs = '';
    $scope.birthday = new Date();
    $scope.degreeYears = application.getDegreeYears();

    $scope.province = '';
    $scope.city = '';
    $scope.provinces = application.getProvinces();
    $scope.cities = new Array();

    $scope.isPublicBirthday = true;
    $scope.isPublicDegree = true;
    $scope.isPublicPhone = true;

    var defer = $q.defer();
    defer.promise
        .then(getJobs($scope, $http))
        .then(function($scope) {
            $scope.getUserInfo()
        });
    defer.resolve($scope, $http);
    $scope.durations = application.getDurations();

    // Province and city cascade
    $scope.cascade = function() {
        $scope.city = '';
        $scope.cities = application.getCities()[$scope.province];
    };

    $scope.jobClick = function(index) {
        $scope.jobs[index].active = !$scope.jobs[index].active;
    };

    $scope.durationClick = function(index) {
        $scope.durations[index].active = !$scope.durations[index].active;
    };

    $scope.getUserInfo = function() {
        $http.get(urls.urlResumeGetProfile).success(function(data) {
            if (data.status == 1) {
                $scope.user = data.url;
                if (isEmpty($scope.user.image_url)) {
                    $scope.user.image_url = paths.pathDefaultAvatar;
                }
                if (!isEmpty($scope.user.birthday)) {
                    $scope.birthday = ($scope.user.birthday).split(' ')[0];
                }
                if (!isEmpty($scope.user.address)) {
                    $scope.province = $scope.user.address.split(',')[0];
                    $scope.cities = application.getCities()[$scope.province];
                    if (!isEmpty($scope.user.address.split(',')[1])) {
                        $scope.city = $scope.user.address.split(',')[1];
                    } else {
                        $scope.city = '';
                    }
                }
                $scope.isPublicBirthday = ($scope.user.ispublic_birthday == 2);
                $scope.isPublicDegree = ($scope.user.ispublic_degree == 2);
                $scope.isPublicPhone = ($scope.user.ispublic_phone == 2);

                setActiveTag($scope.user.jobs, $scope.jobs, 'stat_name');
                setActiveTag($scope.user.duration, $scope.durations, 'id');
            } else {
                $scope.user = '';
            }
        });
    };

    $scope.submit = function() {
        if (!isEmpty($scope.province)) {
            $scope.user.address = $scope.province;
            if (!isEmpty($scope.city)) {
                $scope.user.address += "，" + $scope.city;
            }
        } else {
            $scope.user.address = '';
        }

        var jobs = getActiveTag($scope.jobs, 'stat_name'),
            durations = getActiveTag($scope.durations, 'id'),
            url = urls.urlResumeSubmit,
            data = {
                image_url: $scope.user.image_url,
                user_name: $scope.user.user_name,
                birthday: $scope.birthday,
                jobs: jobs,
                duration: durations,
                sex: $scope.user.sex,
                address: $scope.user.address,
                degree_year: $scope.user.degree_year,
                degree_school: $scope.user.degree_school,
                degree_major: $scope.user.degree_major,
                ispublic_birthday: ($scope.isPublicBirthday * 1 + 1),
                ispublic_degree: ($scope.isPublicDegree * 1 + 1),
                ispublic_phone: ($scope.isPublicPhone * 1 + 1),
                agent_j: $scope.user.agent_j,
                agent_j_desc: $scope.user.agent_j_desc,
                agent_y: $scope.user.agent_y,
                agent_y_desc: $scope.user.agent_y_desc
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    window.location.href = urls.urlResume;
                } else {
                    alert(data.info);
                }
            });
    };

    $scope.imgChange = function(src) {
        $scope.user.image_url = src;
        $scope.$apply();
    };
}]);

// Edit resume extend
function extEditController($scope, $http) {
    $scope.attach = '';
    $scope.images = new Array();
    $scope.scaleTarget = '';
    $scope.spareId = 'image_url1';

    $scope.getAttach = function() {
        var url = urls.urlResumeAttach + '/resume_id/' + $scope.resumeId;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.attach = data.url;
                $scope.images = new Array();
                if (!isEmpty($scope.attach.image)) {
                    for (var i = 0; i < $scope.attach.image.length; i++) {
                        for (img in $scope.attach.image[i]) {
                            $scope.images.push({
                                name: img,
                                url: $scope.attach.image[i][img]
                            });
                        }
                    }
                    genSpareId();
                }
            } else {
                $scope.attach = '';
                $scope.images = new Array();
            }
        });
    };

    $scope.scaleAttach = function(imageIndex) {
        $scope.scaleTarget = $scope.images[imageIndex].url;
    };

    $scope.delAttach = function(imageIndex) {
        var url = urls.urlResumeDelPhoto,
            data = {
                resume_id: $scope.resumeId,
                image_name: $scope.images[imageIndex].name,
                image_url: $scope.images[imageIndex].url
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    $scope.getAttach();
                } else {
                    //                    alert(data.info);
                }
            });
    };

    $scope.delVideo = function() {
        var url = urls.urlResumeDelVideo,
            data = {
                resume_id: $scope.resumeId
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    $scope.getAttach();
                } else {

                }
            });
    };

    // Inform server which slot to put image
    var genSpareId = function() {
        for (var i = 0; i < 8; i++) {
            if (i >= $scope.images.length) {
                $scope.spareId = 'image_url' + (i + Number(1));
                break;
            }

            var str = $scope.images[i].name;
            if (i != Number(str.charAt(str.length - 1)) - 1) {
                $scope.spareId = 'image_url' + (i + Number(1));
                break;
            }
        }
    };
    //
    //    $scope.imgChange = function(src) {
    //        $scope.user.image_url = src;
    //        $scope.$apply();
    //    };

    //    $scope.getAttach();
}

// Message index
function msgController($scope, $http) {
    $scope.msgSys = '';
    $scope.msgUser = '';

    $scope.getMsgSys = function() {
        $http.get(urls.urlMessageGetSys).success(function(data) {
            if (data.status == 1) {
                $scope.msgSys = data.url;
            } else {
                $scope.msgSys = '';
            }
        });
    };

    $scope.getMsgUser = function() {
        $http.get(urls.urlMessageGetUser).success(function(data) {
            if (data.status == 1) {
                $scope.msgUser = data.url;
            } else {
                $scope.msgUser = '';
            }
        });
    };

    $scope.getMsgSys();
    $scope.getMsgUser();
}

// Message flow page
function msgFlowController($scope, $http) {
    $scope.msg = '';

    $scope.getMsg = function() {
        var url = urls.urlMessageRecv + '/publisher_id/' + $('#receiverId').val();
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                $scope.msg = data.url;
            } else {
                $scope.msg = '';
            }
        });
    };

    $scope.submitMsg = function() {
        var url = urls.urlMessageSend,
            data = {
                publisher_id: $('#receiverId').val(),
                content: $scope.content
            };

        $http.post(url, data, postCfg(data))
            .success(function(data) {
                if (data.status == 1) {
                    $scope.content = '';
                    $scope.getMsg();
                } else {
                    //                    alert(data.info);
                }
            });
    };

    $scope.getMsg();
}

// Self settings
function selfController($scope, $http) {
    $scope.user = '';

    $http.get(urls.urlSelfGetInfo).success(function(data) {
        if (data.status == 1) {
            $scope.user = data.url;
            if (isEmpty($scope.user.image_url)) {
                $scope.user.image_url = paths.pathDefaultAvatar;
            }
        } else {
            $scope.user = '';
        }
    });
}

function cloakController($scope, $http) {
    $scope.cloak = function() {
        $http.get(urls.urlSelfCloak).success(function(data) {
            if (data.status == 1) {
                $scope.getUserState();
            }
        });
    };

    $scope.unCloak = function() {
        $http.get(urls.urlSelfUnCloak).success(function(data) {
            if (data.status == 1) {
                $scope.getUserState();
            }
        });
    };
}

// Favorites
function favController($scope, $http) {
    $scope.userFav = '';
    $scope.missionFav = '';

    $scope.getFavUser = function() {
        $http.get(urls.urlFavGetUser).success(function(data) {
            if (data.status == 1) {
                $scope.userFav = data.url;
            } else {
                $scope.userFav = '';
            }
        });
    };

    $scope.getFavMission = function() {
        $http.get(urls.urlFavGetMission).success(function(data) {
            if (data.status == 1) {
                $scope.missionFav = data.url;
                for (var i = 0; i < $scope.missionFav.length; i++) {
                    $scope.missionFav[i].durationMeaning = transDuration($scope.missionFav[i].duration);
                    $scope.missionFav[i].salaryMeaning = transSalary($scope.missionFav[i].salary1,
                        $scope.missionFav.salary2);
                    $scope.missionFav[i].locationMeaning = transLocation($scope.missionFav[i].location1,
                        $scope.missionFav[i].location2);
                }
            } else {
                $scope.missionFav = '';
            }
        });
    };

    $scope.delFavUser = function(user_id) {
        var url = urls.urlFavDelUser + '/user_id/' + user_id;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                //                alert("删除成功");
                $scope.getFavUser();
            } else {

            }
        });
    };

    $scope.delFavMission = function(mission_id) {
        var url = urls.urlFavDelMission + '/mission_id/' + mission_id;
        $http.get(url).success(function(data) {
            if (data.status == 1) {
                //                alert("删除成功");
                $scope.getFavMission();
            } else {

            }
        });
    };


    $scope.getFavUser();
    $scope.getFavMission();
}

// Navigation bar
app.controller('navController', function($scope, $location) {
    var curNav = 0;
    if ($('#curNav').val() != '') {
        curNav = parseInt($('#curNav').val());
    }

    if ($('#entrance').val() == '1') {
        $scope.navItems = application.getNavItems().publisher;
    } else {
        $scope.navItems = application.getNavItems().fetcher;
    }

    //    $scope.selectedItem = 'getmission';
    $scope.itemClick = function(index) {
        $scope.selectedItem = $scope.navItems[index].title;
        window.location.href = $scope.navItems[index].href;
    };

    //Initialization
    //    var curLocation = $location.absUrl();
    if (curNav != -1) {
        $scope.selectedItem = $scope.navItems[curNav].title;
    }
});

app.controller('commonController', function($scope, $http, $timeout) {
    $scope.userState = '';
    $scope.entrance = 0;

    // Get info from session
    $scope.getUserState = function() {
        $http.get(urls.urlGetUserState).success(function(data) {
            if (data.status == 1) {
                $scope.userState = data.url;
            } else {
                $scope.userState = '';
            }
        });
    };

    $scope.getEntrance = function() {
        $http.get(urls.urlGetEntrance).success(function(data) {
            if (data.status == 1) {
                $scope.entrance = data.url;
            } else {
                $scope.entrance = 0;
            }
        });
    };

    // Calculate time duration
    $scope.getTimePast = function(datetime) {
        if (!isEmpty(datetime)) {
            var curTime = new Date(),
                pastTime = new Date(datetime.replace(' ', 'T') + '+08:00'),
                duration = 0,
                result = '';
            duration = (curTime.getTime() - pastTime.getTime()) / 1000;
            if (duration > 0 && duration < 60) {
                result = '刚刚';
            } else if (duration >= 60 && duration < 60 * 60) {
                result = Math.ceil(duration / 60) + '分钟前';
            } else if (duration >= 60 * 60 && duration < 60 * 60 * 24) {
                result = Math.ceil(duration / (60 * 60)) + '小时前'
            } else if (duration >= 60 * 60 * 24) {
                result = Math.ceil(duration / (60 * 60 * 24)) + '天前'
            }
            return result;
        }
    };
});

// Favorite user
function favUser(userId, $http) {
    var url = urls.urlFavUser + '/user_id/' + userId;
    $http.get(url).success(function(data) {
        if (data.status == 1) {
            //            alert("收藏成功");
        } else {

        }
    });
}

function delFavUser(userId, $http) {
    var url = urls.urlFavDelUser + '/user_id/' + userId;
    $http.get(url).success(function(data) {
        if (data.status == 1) {
            //                alert("删除成功");
        } else {

        }
    });
}

// Tag list utils
function setActiveTag(arr, tags, field) {
    if (!isEmpty(arr)) {
        for (var i = 0; i < tags.length; i++) {
            if (arr.indexOf(tags[i][field]) != -1) {
                tags[i].active = true;
            }
        }
    }
}

function getActiveTag(arr, field) {
    var result = '';
    var tempArr = new Array();
    for (var i = 0; i < arr.length; i++) {
        if (arr[i].active) {
            tempArr.push(arr[i][field]);
        }
    }
    result = tempArr.join(',');
    return result;
}

// Generate degrees split with commas
function genDegreeInfo(info) {
    var resultArr = new Array();
    if (!isEmpty(info.degree_year))
        resultArr.push(info.degree_year + '级');
    if (!isEmpty(info.degree_school))
        resultArr.push(info.degree_school);
    if (!isEmpty(info.degree_major))
        resultArr.push(info.degree_major);
    return resultArr.join('，');
}

function getJobs($scope, $http) {
    $http.get(urls.urlGetJobs).success(function(data) {
        if (data.status == 1) {
            $scope.jobs = data.url;
            for (var i = 0; i < $scope.jobs.length; i++) {
                $scope.jobs[i].active = false;
            }
            // Initialize job list active state
            //            $scope.jobs[0].active = $scope.durations[0].active = true;
            // Hide more jobs
            if ($scope.jobs.length > 2) {
                $scope.limit = 2;
            }
        } else {
            $scope.jobs = '';
        }
    });
}

// Field translation utils
function transJobs(jobs) {
    if (!isEmpty(jobs))
        return jobs.replace(/,/g, '，');
    else
        return '';
}

function transDuration(duration) {
    var durations = new Array();
    var result = new Array();
    if (!isEmpty(duration)) {
        durations = duration.split(',');
        for (var i = 0; i < durations.length; i++) {
            result.push(application.getDurations()[durations[i] - 1].name);
        }
    }
    return result.join('，');
}

function transSalary(salary1, salary2) {
    var result = '';
    if (salary1 == 1) {
        result = salary2;
    } else if (salary1 == 2 || salary1 == 3) {
        result = application.getSalary()[salary1 - 1].name;
    }
    return result;
}

function transLocation(location1, location2) {
    var result = '';
    if (location1 == 3) {
        result = location2;
    } else if (location1 == 1 || location1 == 2) {
        result = application.getLocations()[location1 - 1].name;
    }
    return result;
}

// General utils
function postCfg(data) {
    return {
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        transformRequest: function(data) {
            return $.param(data);
        }
    };
}

function isEmpty(obj) {
    return (obj == '' || obj == null || obj == undefined);
}

function isPC()
{
    var userAgentInfo = navigator.userAgent;
    var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; }
    }
    return flag;
}